import cherrypy as httpd
from orbit.simple import Client
httpd.config.update(file="chat.cfg") 

orbit = Client()
orbit.connect()

class ChatServer(object):
    users = []    
    def join(self, user, session='0', id=None):
        if (user, session) not in self.users:
            self.users.append((user, session))
        try:
            orbit.event(['%s, %s, /ajax' % (u, s) for u,s in self.users ], 
                         '<b>%s joined</b>' % (user,))
        except:
            orbit.connect() 
            orbit.event(['%s, %s, /ajax' % (u, s) for u,s in self.users ], 
                         '<b>%s joined</b>' % (user,))
            
        return ""        
    join.exposed = True
    
    def msg(self, user, msg,session='0', id=None):

        try:
            orbit.event(['%s, %s, /ajax' % (u, s) for u,s in self.users ], 
                         '<b>%s</b> %s' % (user, msg))
        except:
            orbit.connect()
            orbit.event(['%s, %s, /ajax' % (u, s) for u,s in self.users ], 
                        '<b>%s</b> %s' % (user, msg))
                
        return ""
    msg.exposed = True
    
httpd.root = ChatServer()
httpd.server.start()
